from datetime import datetime, timedelta

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from Util.SQL import *
from Util.Return import get_image, get_location
from Util.Image import tiff_to_other_data


@csrf_exempt
def index(request):
    if request.method == "GET":
        position1 = request.session.get('position1', 0)  # 若从变化页面返回本页面时，position1为-1，页面显示查询不到变化信息
        context = {'position1': position1}  # 未进行查询，position1返回默认值
        return render(request, 'index.html', context)
    # data_list = request.session.get('data_list', [])  # 读取缓存
    datatype = request.POST.get('datatype', '-2')  # 原始数据 1 /变化数据 0
    position1 = request.POST.get('position1', '0')  # 读取输入位置
    # 变化数据
    if datatype == "0":
        tiff_to_other_data("../static/images/20230712_20230724_color.tif",
                           "../static/images/20230712_20230724_color.png")
        sc, boundary = get_location(position1, True)  # 获取bbox值
        if sc == -1:  # 获取不到bbox值
            sc, boundary = get_location(position1, False)  # 获取经纬度
            print(sc, boundary)
            if sc != -1:  # 获取到经纬度
                ori_string = "\
                    SELECT event_id,date,bbox,information,address,location_list,a,b,c,d\
                        FROM (\
                            SELECT \
                                event_id,date,bbox,attribute as information,address,location_list,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 1), '(', -1) AS DECIMAL(10, 5)) AS a,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 2), ', ', -1) AS DECIMAL(10, 5)) AS b,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 3), ', ', -1) AS DECIMAL(10, 5)) AS c,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', -1), ')', 1) AS DECIMAL(10, 5)) AS d\
                            FROM event\
                        ) AS temp\
                    WHERE \
                        a < @ \
                        AND b < # \
                        AND c > @ \
                        AND d > #;"
                sql_string = ori_string.replace("@", str(sc['lng'])).replace("#", str(sc['lat']))
                result = select(sql_string)  # 获取符合该经纬度的数据
            else:
                result = []  # 未获取到经纬度，赋初值
        else:
            # start = time.perf_counter()
            ori_string = "\
                    SELECT event_id,date,bbox,information,address,location_list,a,b,c,d\
                        FROM (\
                            SELECT \
                                event_id,date,bbox,attribute as information,address,location_list,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ',', 1), '(', -1) AS DECIMAL(10, 5)) AS a,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ',', 2), ',', -1) AS DECIMAL(10, 5)) AS b,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ',', 3), ',', -1) AS DECIMAL(10, 5)) AS c,\
                                CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ',', -1), ')', 1) AS DECIMAL(10, 5)) AS d\
                            FROM event\
                        ) AS temp\
                        WHERE \
                            (c>@ AND a<$) AND (d># AND b<%);"
            sql_string = ori_string.replace("@", str(sc[0])).replace("#", str(sc[1])).replace("$", str(sc[2])).replace(
                "%", str(sc[3]))
            result = select(sql_string)  # 获取符合该bbox的数据
        if len(result) == 0:
            return JsonResponse({'event_id': 0, 'date': 0, 'bbox': 0, 'information': 0, 'address': 0, 'boundary': 0,
                                 'len': 0})
        key_value_lists = {}
        # 遍历字典数组
        for d in result:
            # 遍历每个字典的键值对
            for key, value in d.items():
                # 如果 key 不在 key_value_lists 中，则初始化一个空列表
                if key not in key_value_lists:
                    key_value_lists[key] = []
                # 将值添加到对应的键的值列表中
                if key == 'date':
                    value = value.strftime("%Y-%m-%d")
                if key == 'a' or key == 'b' or key == 'c' or key == 'd':
                    value = float(value)
                key_value_lists[key].append(value)
        coordinates_list = []
        for item in key_value_lists['location_list']:
            tmp = []
            coordinates_str = item[2:-2].split('),(')
            for point in coordinates_str:
                tmp.append([float(point.split(',')[0]), float(point.split(',')[1])])
            coordinates_list.append(tmp)
        bbox = []
        lenth = len(key_value_lists['a'])
        for i in range(lenth):
            bbox.append(
                [key_value_lists['a'][i], key_value_lists['b'][i], key_value_lists['c'][i], key_value_lists['d'][i]])
        content = {'event_id': key_value_lists['event_id'], 'date': key_value_lists['date'],
                   'bbox': bbox,
                   'information': key_value_lists['information'], 'address': key_value_lists['address'],
                   'boundary': coordinates_list, 'len': 1}
        return JsonResponse(content)
    # 原始数据
    current_time = datetime.now().strftime('%Y-%m-%d')
    startdate = request.POST.get('startdate', '0')  # 读取输入开始时间
    enddate = request.POST.get('enddate', '0')  # 读取输入结束时间
    current_date = datetime.now()
    three_months_ago = current_date - timedelta(days=90)
    formatted_date = three_months_ago.strftime("%Y-%m-%d")
    if len(startdate) == 0 & len(enddate) == 0:  # 处理用户未输入完全日期的情况
        startdate = formatted_date
        enddate = current_time
    elif len(startdate) == 0:
        startdate = enddate
    elif len(enddate) == 0:
        enddate = current_time
    date = [startdate, enddate]

    sc, boundary = get_location(position1, True)  # 获取bbox值
    if sc == -1:  # 获取不到bbox值
        sc, boundary = get_location(position1, False)  # 获取经纬度
        if sc != -1:  # 获取到经纬度
            ori_string = "\
            SELECT scene_id,data_id,date,bbox,dataset,cbox,type,satellite,available,address,json,product,a,b,c,d\
                FROM (\
                    SELECT \
                        scene_id, data_id, date, bbox, dataset, cbox, type, satellite, available,address, json,product,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 1), '(', -1) AS DECIMAL(10, 5)) AS a,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 2), ', ', -1) AS DECIMAL(10, 5)) AS b,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 3), ', ', -1) AS DECIMAL(10, 5)) AS c,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', -1), ')', 1) AS DECIMAL(10, 5)) AS d\
                    FROM data\
                ) AS temp\
            WHERE \
                a < @ \
                AND b < # \
                AND c > @ \
                AND d > #\
                AND available=1\
                AND product != 'SLC' \
                AND (date BETWEEN '&' AND '~' OR type = 'Feature');"
            sql_string = ori_string.replace("@", str(sc['lng'])).replace("#", str(sc['lat'])).replace("&", str(date[0])).replace("~", str(date[1]))
            result = select(sql_string)  # 获取符合该经纬度的数据
        else:
            result = []  # 未获取到经纬度，赋初值
    else:
        # start = time.perf_counter()
        ori_string = "\
            SELECT scene_id,data_id,date,bbox,dataset,cbox,type,satellite,available,address,json,product,a,b,c,d\
                FROM (\
                    SELECT \
                        scene_id,data_id,date,bbox,dataset,cbox,type,satellite,available,address,json,product,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 1), '(', -1) AS DECIMAL(10, 5)) AS a,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 2), ', ', -1) AS DECIMAL(10, 5)) AS b,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', 3), ', ', -1) AS DECIMAL(10, 5)) AS c,\
                        CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(bbox, ', ', -1), ')', 1) AS DECIMAL(10, 5)) AS d\
                    FROM data\
                ) AS temp\
                WHERE \
                    (c>@ AND a<$) AND (d># AND b<%) AND available=1\
                    AND (date BETWEEN '&' AND '~' OR type = 'Feature');"
        sql_string = ori_string.replace("@", str(sc[0])).replace("#", str(sc[1])).replace("$", str(sc[2])).replace("%",str(sc[3])).replace("&", str(date[0])).replace("~", str(date[1]))
        result = select(sql_string)  # 获取符合该bbox的数据
        # end = time.perf_counter()
    filtered_result = [item for item in result if "SLC" not in item.get("scene_id")]
    if filtered_result is None:
        context = {'scenes': -1, 'sc': sc, 'boundary': boundary}  # bbox和经纬度都找不到
    else:
        imgs = []
        for items in filtered_result:  # 获取所有符合的图片
            img = get_image("quick_look", items["scene_id"])
            imgs.append(img)
            if items["scene_id"][0] == 'S':
                items["display"] = items["scene_id"][0:6]
            else:
                items["display"] = items["scene_id"][0:9]
        if isinstance(sc, tuple):
            jud = 1
        else:
            jud = 0
        context = {'scenes': filtered_result, 'sc': sc, 'jud': jud, 'boundary': boundary, 'imgs': imgs}
    return JsonResponse(context)


def findimg(request, nid, datatype):
    img = get_image(int(datatype), nid)
    context = {'img': img}
    return JsonResponse(context)
